<template>
  <div class="traffic-stats">
    <!-- 流量卡片 -->
    <div class="stat-cards">
      <div class="stat-card">
        <div class="stat-label">日流量</div>
        <div class="stat-value">{{ day }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">周流量</div>
        <div class="stat-value">{{ week }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">月流量</div>
        <div class="stat-value">{{ month }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">年流量</div>
        <div class="stat-value">{{ year }}</div>
      </div>
    </div>
    <!-- 近30天流量趋势图表 -->
    <div class="chart-section">
      <div class="chart-title" style="color: deepskyblue">近30天每日流量</div>
      <div class="chart-container" ref="dailyChart"></div>
    </div>
    <!-- 底部两个图表 -->
    <div class="bottom-charts">
      <div class="chart-section">
        <div class="chart-title" style="color: #6b7280">栏目浏览统计TOP10</div>
        <div class="chart-container" ref="categoryChart"></div>
      </div>
      <div class="chart-section">
        <div class="chart-title" style="color: #6b7280">文章浏览统计TOP10</div>
        <div class="chart-container" ref="articleChart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getAllTrafficData } from '@/api/system/picture';

export default {
  name: 'TrafficStats',
  data() {
    return {
      day: 0,
      week: 0,
      month: 0,
      year: 0,
      dailyData: { dates: [], values: [] },
      categoryData: [],
      articleData: []
    };
  },
  mounted() {
    this.fetchAllData();
    // 优化：使用箭头函数确保this指向正确
    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    // 优化：移除事件监听，防止内存泄漏
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      // 优化：统一处理图表 resize
      const charts = [
        this.$refs.dailyChart,
        this.$refs.categoryChart,
        this.$refs.articleChart
      ];
      charts.forEach(dom => {
        if (dom) {
          const chart = echarts.getInstanceByDom(dom);
          chart && chart.resize();
        }
      });
    },

    renderDailyChart() {
      const chartDom = this.$refs.dailyChart;
      if (!chartDom || this.dailyData.dates.length === 0) return; // 优化：空数据不渲染

      const myChart = echarts.init(chartDom);
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#eeeeee',
          borderColor: '#ccc',
          borderWidth: 1,
          padding: 10,
          formatter: (params) => `
            <div style="font-size: 12px;">
              <div>${params[0].name}</div>
              <div>浏览量: ${params[0].value}</div>
            </div>
          `
        },
        xAxis: {
          type: 'category',
          data: this.dailyData.dates,
          axisLine: { lineStyle: { color: '#ccc' } },
          axisTick: { show: false },
          axisLabel: { color: '#666', fontSize: 10, margin: 5 }
        },
        yAxis: {
          type: 'value',
          min: 0,
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { lineStyle: { color: '#eee', type: 'dashed' } },
          axisLabel: { color: '#666', fontSize: 10 }
        },
        series: [{
          name: '日流量',
          type: 'line',
          data: this.dailyData.values,
          smooth: false,
          symbol: 'circle',
          symbolSize: 4,
          itemStyle: { color: '#c3b1e1', borderColor: '#fff', borderWidth: 1 },
          lineStyle: { color: '#c3b1e1', width: 1.5 },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(195, 177, 225, 0.2)' },
              { offset: 1, color: 'rgba(195, 177, 225, 0)' }
            ])
          }
        }],
        grid: { left: '2%', right: '2%', bottom: '15%', top: '15%', containLabel: true }
      });
    },

    renderCategoryChart() {
      const chartDom = this.$refs.categoryChart;
      if (!chartDom || this.categoryData.length === 0) return; // 优化：空数据不渲染

      const myChart = echarts.init(chartDom);
      myChart.setOption({
        tooltip: { trigger: 'item' },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'center',
          textStyle: { color: '#666', fontSize: 12 }
        },
        series: [{
          name: '栏目浏览量',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['65%', '50%'],
          data: this.categoryData,
          itemStyle: {
            color: (params) => {
              const colors = [
                '#FF6B6B', '#F06292', '#BA68C8', '#9575CD', '#7986CB',
                '#64B5F6', '#4FC3F7', '#4DD0E1', '#4DB6AC', '#81C784'
              ];
              return colors[params.dataIndex % colors.length];
            },
            borderColor: '#fff',
            borderWidth: 2
          },
          emphasis: {
            itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.1)' }
          }
        }]
      });
    },

    renderArticleChart() {
      const chartDom = this.$refs.articleChart;
      if (!chartDom || this.articleData.length === 0) return; // 优化：空数据不渲染

      const myChart = echarts.init(chartDom);
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          backgroundColor: '#eeeeee',
          borderColor: '#ccc',
          borderWidth: 1
        },
        grid: { left: '3%', right: '3%', bottom: '3%', top: '3%', containLabel: true },
        xAxis: {
          type: 'value',
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { lineStyle: { color: '#eee', type: 'dashed' } },
          axisLabel: { color: '#666', fontSize: 10 }
        },
        yAxis: {
          type: 'category',
          data: this.articleData.map(item => item.name),
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { color: '#666', fontSize: 10, width: 80, overflow: 'truncate' }
        },
        series: [{
          name: '文章浏览量',
          type: 'bar',
          data: this.articleData.map(item => item.value),
          itemStyle: {
            color: (params) => {
              const colors = [
                '#FF6B6B', '#F06292', '#BA68C8', '#9575CD', '#7986CB',
                '#64B5F6', '#4FC3F7', '#4DD0E1', '#4DB6AC', '#81C784'
              ];
              return colors[params.dataIndex % colors.length];
            }
          },
          barWidth: '60%'
        }]
      });
    },

    async fetchAllData() {
      try {
        const response = await getAllTrafficData();
        // 优化：严格校验接口响应结构
        if (!response || response.code !== 200 || !response.data) {
          console.error('接口返回格式错误', response);
          return;
        }

        const { traffic, trafficByDay, top10, top10Article } = response.data;
        // 优化：初始化默认空值，避免解构报错
        const safeTraffic = traffic || { daily: {}, weekly: {}, monthly: {}, yearly: {} };
        const safeTrafficByDay = trafficByDay || [];
        const safeTop10 = top10 || [];
        const safeTop10Article = top10Article || [];

        // 处理日/周/月/年流量（与后端getTraffic()返回结构完全适配）
        this.day = safeTraffic.daily?.total_visits || 0;
        this.week = safeTraffic.weekly?.total_visits || 0;
        this.month = safeTraffic.monthly?.total_visits || 0;
        this.year = safeTraffic.yearly?.total_visits || 0;

        // 处理近30天流量（兼容后端字段名）
        this.dailyData = {
          dates: safeTrafficByDay.map(item => item.browse_date || '未知日期'), // 优化：默认值
          values: safeTrafficByDay.map(item => item.browse_count || 0)
        };
        this.renderDailyChart();

        // 处理栏目前十
        this.categoryData = safeTop10.map(item => ({
          name: item.column_name || '未知栏目', // 优化：默认值
          value: item.browse_count || 0
        }));
        this.renderCategoryChart();

        // 处理文章前十
        this.articleData = safeTop10Article.map(item => ({
          name: item.article_name || '未知文章', // 优化：默认值
          value: item.article_browse_count || 0
        }));
        this.renderArticleChart();

      } catch (error) {
        console.error('获取数据失败', error);
        // 优化：错误状态下重置数据，避免页面异常
        this.resetData();
      }
    },

    resetData() {
      // 错误时重置数据，保证页面正常显示
      this.day = this.week = this.month = this.year = 0;
      this.dailyData = { dates: [], values: [] };
      this.categoryData = [];
      this.articleData = [];
    }
  }
};
</script>

<style scoped>
.traffic-stats {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px 0;
  box-sizing: border-box;
  gap: 20px;
}

.stat-cards {
  display: flex;
  justify-content: space-around;
  width: 100%;
}

.stat-card {
  flex: 1;
  max-width: 280px;
  margin: 0 10px;
  padding: 20px;
  text-align: center;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  background-color: #fff;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-label {
  font-size: 16px;
  color: #6b7280;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #111827;
}

.chart-section {
  width: 100%;
  background-color: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 15px;
  box-sizing: border-box;
}

.chart-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
}

.chart-container {
  width: 100%;
  height: 150px;
}

.bottom-charts {
  display: flex;
  width: 100%;
  gap: 20px;
}

.bottom-charts .chart-section {
  flex: 1;
}

@media (max-width: 768px) {
  .bottom-charts {
    flex-direction: column;
  }
}
</style>
